const { parse } = require("url");

const send = require("../send");
const transformRequest = require("../transformRequest");

const knowJsSrcRE = /\.js/;

function isJSRequest(url) {
  return knowJsSrcRE.test(url);
}

function transformMiddleware(server) {
  console.log("DDDDDDDDDDDDDDDDDDDDDD");
  return async function (req, res, next) {
    if (req.method !== "GET") {
      return next();
    }
    let url = parse(req.url).pathname;
    if (isJSRequest(url)) {
      const result = await transformRequest(url, server);
      console.log("result, result", result);
      if (result) {
        return send(req, res, result.code, "js");
      } else {
        return next();
      }
    } else {
      return next();
    }
  };
}

module.exports = transformMiddleware;
